//
//  ModelProduct.m
//  MexicoLoan
//
//  Created by wxp on 2025/3/15.
//

#import "ModelProduct.h"
#import "ModelProductPackageList.h"

NSString *const kModelProductAmount = KEY_amount;
NSString *const kModelProductProductPackageList = KEY_ProductPackageList;

@interface ModelProduct ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation ModelProduct

@synthesize amount = _amount;
@synthesize productPackageList = _productPackageList;

+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)dict {
    self = [super init];
    
    if (self && [dict isKindOfClass:[NSDictionary class]]) {
        self.amount = [[self objectOrNilForKey:kModelProductAmount fromDictionary:dict] doubleValue];
        NSObject *receivedProductPackageList = [dict objectForKey:kModelProductProductPackageList];
        NSMutableArray *parsedProductPackageList = [NSMutableArray array];
        if ([receivedProductPackageList isKindOfClass:[NSArray class]]) {
            for (NSDictionary *item in (NSArray *)receivedProductPackageList) {
                if ([item isKindOfClass:[NSDictionary class]]) {
                    [parsedProductPackageList addObject:[ModelProductPackageList modelObjectWithDictionary:item]];
                }
            }
        } else if ([receivedProductPackageList isKindOfClass:[NSDictionary class]]) {
            [parsedProductPackageList addObject:[ModelProductPackageList modelObjectWithDictionary:(NSDictionary *)receivedProductPackageList]];
        }
        self.productPackageList = [NSArray arrayWithArray:parsedProductPackageList];
    }
    return self;
}

- (NSDictionary *)dictionaryRepresentation {
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:[NSNumber numberWithDouble:self.amount] forKey:kModelProductAmount];
    NSMutableArray *tempArrayForProductPackageList = [NSMutableArray array];
    for (NSObject *subArrayObject in self.productPackageList) {
        if ([subArrayObject respondsToSelector:@selector(dictionaryRepresentation)]) {
            [tempArrayForProductPackageList addObject:[subArrayObject performSelector:@selector(dictionaryRepresentation)]];
        } else {
            [tempArrayForProductPackageList addObject:subArrayObject];
        }
    }
    [mutableDict setValue:[NSArray arrayWithArray:tempArrayForProductPackageList] forKey:kModelProductProductPackageList];
    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description  {
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict {
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}

@end
